/* Copyright 2012 Oliver Katz

    This file is part of Theta.

    Theta is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>. */

#include "dyndir.h"

namespace compiler
{
	namespace dyndir
	{
		DynamicDirectory::DynamicDirectory()
		{
		}

		DynamicDirectory::DynamicDirectory(string r)
		{
			string cmd = "mkdir /dev/shm/"+r;
			system(cmd.c_str());
			root = "/dev/shm/"+r;
		}

		void DynamicDirectory::addSubDirectory(string name)
		{
			string cmd = "mkdir "+root+"/"+name;
			system(cmd.c_str());
			subdirs.push_back(name);
		}

		void DynamicDirectory::addFile(string subdir, string name)
		{
			files[subdir].push_back(name);
		}

		string DynamicDirectory::set(string subdir, string name, string value)
		{
			stringstream ss;
			ss << root << "/" << subdir << "/" << name;
			FILE *f = fopen(ss.str().c_str(), "w");
			fputs(value.c_str(), f);
			fclose(f);
			return value;
		}

		string DynamicDirectory::get(string subdir, string name)
		{
			stringstream ss;
			ss << root << "/" << subdir << "/" << name;
			FILE *f = fopen(ss.str().c_str(), "r");
			char *buf = (char *)malloc(sizeof(char)*128);
			fgets(buf, 128, f);
			fclose(f);
			*(strchr(buf, '\n')) = 0;
			return string(buf);
		}

		void DynamicDirectory::cleanup()
		{
			stringstream ss;
			ss << "rm -rf " << root;
			system(ss.str().c_str());
		}

		void DynamicDirectory::lock()
		{
			stringstream ss;
			ss << root << "/.lock";
			FILE *f = fopen(ss.str().c_str(), "w");
			fputs("", f);
			fclose(f);
		}

		bool DynamicDirectory::checkLock()
		{
			stringstream ss;
			ss << root << "/.lock";
			FILE *f = fopen(ss.str().c_str(), "r");
			if (f == NULL)
				return false;
			fclose(f);
			return true;
		}
	}
}